package isp

import (
    `errors`
)

// 04_repeated_inputs 重复输入

type Value interface {
    Value(key interface{}) interface{}
}

type Mointor interface {
    Done() <-chan struct{}
}

func EncryptV2(keyValue Value, monitor Mointor, data []byte) ([]byte, error) {
    // As this operation make take too long, we need to be able to kill it
    //     因为这个操作需要花费太长时间，我们需要能够杀死它。
    stop := monitor.Done()
    result := make(chan []byte, 1)

    go func() {
        defer close(result)

        // pull the encryption key from context 从上下文中提取加密密钥
        key := keyValue.Value("encryption-key").([]byte)

        // perform encryption 执行加密
        ciperText := performEncryption(key, data)

        // signal complete by sending the result 通过发送结果完成信号
        result <- ciperText
    }()

    select {
    case ciperText := <-result:
        // happy path
        return ciperText, nil
    case <-stop:
        // cancelled
        return nil, errors.New("operation cancelled")
    }

}
